package com.xie.headline.sso.service.impl;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xie.headline.sso.common.JsonResult;
import com.xie.headline.sso.domain.dto.WmUserDto;
import com.xie.headline.sso.domain.po.WmUser;
import com.xie.headline.sso.domain.vo.WmUserVO;
import com.xie.headline.sso.mapper.WmUserMapper;
import com.xie.headline.sso.service.WmUserService;
import com.xie.headline.sso.utils.BCryptPasswordEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WmUserServiceImpl extends SuperServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Autowired
    private WmUserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private String Key = "123456";

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public JsonResult loginByUserName(WmUserDto dto) {
        // 根据用户名来查询数据
        LambdaQueryWrapper<WmUser> wapper = new LambdaQueryWrapper<>();
        wapper.eq(WmUser::getName, dto.getName());
        WmUser wmUser = userMapper.selectOne(wapper);
        // 如果无此用户则返回null
        if (wmUser == null) {
            return JsonResult.error("用户不存在");
        }
        // 将前端输入的密码进行ss加密后打印出来
        log.info(bCryptPasswordEncoder.encode(dto.getPassword()));
        // 判断前端传来的密码与用户名查出来的用户密码是否相同
        if (!bCryptPasswordEncoder.matches(dto.getPassword(), wmUser.getPassword())){
            // 不同则返回null
            return JsonResult.error("用户名或者密码错误");
        }
        // 相同则签发token
        String token = JWT.create()
                .setPayload("id",wmUser.getId())
                // todo:这里的key临时设置，后续需要添加到配置文件中，并且需要记得添加token的过期时间
                .setKey(Key.getBytes())
                .sign();
        WmUserVO vo = new WmUserVO();
        vo.setUsername(dto.getName());
        vo.setToken(token);
        return JsonResult.success(vo);
    }
}
